var express = require("express");
var router = express.Router();

// 用于生成密钥对
const NodeRSA = require("node-rsa");
// 密文的最大长度是512位
const key = new NodeRSA({ b: 1024 });
// 一种加密的填充方案
key.setOptions({ encryptionScheme: "pkcs1" });

const Users = require("../models/users");

const jwt = require("jsonwebtoken");

// 预登录
router.get("/key", (req, res, next) => {
  let publicKey = key.exportKey("public"); //生成公钥
  // console.log(publicKey);
  res.json({
    key: publicKey,
  });
});

/* GET users listing. */
// 登录接口
router.post("/login", function (req, res, next) {
  const { info } = req.body;
  // console.log(info);

  let decrypted = key.decrypt(info, "utf8"); //解密
  // console.log(decrypted);
  const { username, password } = JSON.parse(decrypted);

  if (!username || !password) {
    res.json({
      status: 1001,
      msg: "参数错误",
    });
  } else {
    Users.findOne({ username }, (err, doc) => {
      if (doc) {
        if (doc.password === password) {
          // 在登录成功以后生成token
          let payload = { name: username, password: password };
          let secret = "I_LOVE_JING";
          // 第三个参数表示token的时效
          let token = jwt.sign(payload, secret, { expiresIn: 60 * 1 });
          // console.log(token);
          // 传给前端
          res.json({
            status: 0,
            msg: "登录成功",
            token,
          });
        } else {
          res.json({
            status: 1004,
            msg: "密码错误",
          });
        }
      } else {
        res.json({
          status: 1003,
          msg: "该用户不存在",
        });
      }
    });
  }
});

module.exports = router;
